﻿package test;

/**
 * 题目：线程1执行2次，线程2执行3次，线程1在执行2次，线程2再执行3次，这样循环3次
 * */
public class LangDemo1 {

	public static void main(String[] args) {
		new LangDemo1().init();
	}

	public void init() {
		final X x = new X();
		new Thread(new Runnable() {
			public void run() {
				//总共循环3次
				for (int i = 0; i < 3; i++) {
					x.threadone();
				}
			}
		}).start();
		
		new Thread(new Runnable() {
			public void run() {
				//总共循环3次
				for (int i = 0; i < 3; i++) {
					x.threadtwo();
				}
			}
		}).start();
	}
	//内部类
	class X {
		boolean flag = false;
		int countone = 0;
		int counttwo = 0;

		public synchronized void threadone() {
			countone++;
			if (flag) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			//线程1的2次循环
			for (int i = 0; i < 2; i++) {
				System.out.println(Thread.currentThread().getName());
			}
			this.notify();
			flag = true;
			System.out.println("threadone is runing the " + countone + " time");
		}

		public synchronized void threadtwo() {
			counttwo++;
			if (!flag) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			//线程2的3次循环
			for (int i = 0; i < 3; i++) {
				System.out.println(Thread.currentThread().getName());
			}
			this.notify();
			flag = false;
			System.out.println("threadtwo is runing the " + countone + " time");
		}
	}
}
